package com.museum.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.museum.base.BaseApiService;
import com.museum.base.BaseResponse;
import com.museum.core.utils.RedisUtil;
import com.museum.entity.DO.Token;
import com.museum.entity.DO.User;
import com.museum.entity.DO.UserRole;
import com.museum.entity.DTO.RedisInfo.UserMessage;
import com.museum.entity.DTO.role.UserRoleDTO;
import com.museum.entity.DTO.user.UserAdd;
import com.museum.entity.DTO.user.UserAll;
import com.museum.entity.DTO.user.UserQuery;
import com.museum.entity.DTO.user.userAreaDTO;
import com.museum.mapper.*;
import com.museum.service.api.UserServiceAPI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author LB
 * @version 1.0
 * @date 2020/12/21 11:26
 */
@Service
public class UserServiceImpl extends BaseApiService<JSONObject> implements UserServiceAPI {
    public static final Object lock=1;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AreaPermissionMapper apMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private TokenMapper tokenMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public   BaseResponse<JSONObject> userAdd(HttpServletRequest request, UserAdd userAdd) {
        synchronized (this){
            String token = request.getHeader("Authorization");
            if (token == null) {
                return setResultError("token失效");
            }
            String infos = redisUtil.getString(token);
            UserMessage info = JSONObject.parseObject(infos, UserMessage.class);
            if (info==null) return setResultError("token is Null !");
            //获取地域编号
            Integer areaNumber = info.getAreaNumber();

            int count = areaMapper.selectCountByNumber(areaNumber);
            if (count <= 0) {
                return setResultError("请添加正确的地域信息");
            }
            String userName = userAdd.getUserName();
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", userName));
            if (user != null) {
                return setResultError(202, "该用户已经存在");
            }
            User user2 = new User();
            BeanUtils.copyProperties(userAdd, user2);
            user2.setAreaNumber(areaNumber);
            user2.setUserStatus(0);
            userMapper.insert(user2);
            Integer roleId = userAdd.getRoleId();
            UserRole userRole = new UserRole();
            if (StringUtils.isEmpty(roleId) || roleId == 0) {
                userRole.setRoleId(200);
                userRole.setUserId(user2.getUserId());
                userRoleMapper.insert(userRole);
            } else {
                //前端传入了对应的角色 分配对应的角色
                userRole.setRoleId(roleId);
                userRole.setUserId(user2.getUserId());
                userRoleMapper.insert(userRole);
            }
        }

        return setResultSuccess(200, "添加成功");
    }

    @Override
    public BaseResponse<JSONObject> deleteUserById(HttpServletRequest request, Integer userId) {
        String token = request.getHeader("Authorization");
        if (token == null) {
            return setResultError("token失效");
        }
        String infos = redisUtil.getString(token);
        UserMessage info = JSONObject.parseObject(infos, UserMessage.class);
        if (info != null) {
            if (info.getUserId().equals(userId)) return setResultError("无法删除自己！");
            String userName = userMapper.getUserNameById(userId);
            if (userName.equals("超级管理员")) {
                return setResultError(205, "超级管理员无法删除");
            }
            //删除用户
            int delete = userMapper.delete(new QueryWrapper<User>().eq("user_id", userId));
            if (delete == 1) {
                userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));
                //更新用户的状态 将该用户的token置为1
                Token oldToken = tokenMapper.selectOne(new QueryWrapper<Token>().eq("userId", userId).eq("isAvailability", 0));
                if (oldToken != null) {
                    oldToken.setIsAvailability(1);
                    tokenMapper.updateById(oldToken);
                    String OtherToken = oldToken.getToken();
                    String flag = redisUtil.getString(OtherToken);
                    if (!StringUtils.isEmpty(flag)) {
                        redisUtil.delKey(OtherToken);
                    }
                }
            } else {
                return setResultError("系统错误,删除失败");
            }
            //删除用户对应的角色
            return setResultSuccess("删除成功");
        } else {
            return setResultError("系统错误");
        }
    }

    @Override
    public BaseResponse<JSONObject> updateUser(HttpServletRequest request, UserAdd user) {
        Integer roleId = user.getRoleId();
        String token = request.getHeader("Authorization");
        if (token == null) {
            return setResultError("token失效");
        }
        int roleFlag = 0;
        Integer userId = user.getUserId();
        if(StringUtils.isEmpty(roleId)||roleId==0) {
            return setResultError("请正确的修改角色");
        }else{
        //根据用户userId 拿到roleId 根据roleId 判断level是不是0
            int level = roleMapper.getLevelByRoleId(roleId);
            if(level==0){
                //默认角色 level=0
                roleFlag =1;
            }
            if(roleFlag==0){
                //判断选择的角色 在该地域是否存在
                int flag = roleMapper.selectCountByArea(roleId, user.getAreaNumber());
                if(flag<=0){
                    return setResultError("该地区无此角色");
                }else{
                userRoleMapper.updateByUserId(user.getUserId(), roleId);
                }
            }else{
                userRoleMapper.updateByUserId(user.getUserId(),roleId);
            }
        }

        String userName = user.getUserName();
        User user2 = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", userName).ne("user_id", userId));
        if (user2 != null && user2.getUserName().equals(user.getUserName())) {
            return setResultError(202, "该用户已经存在");
        }
        User userEnd = new User();
        BeanUtils.copyProperties(user, userEnd);
        System.out.println("修改的角色=" + userEnd);
        int i = userMapper.updateById(userEnd);
        if (i > 0) {
            return setResultSuccess(200, "修改成功");
        } else {
            return setResultError(202, "修改失败");
        }
    }


    @Override
    public userAreaDTO selectById(HashMap<String, Object> map) {
        return userMapper.getUserInfoByIds(map);
    }

    @Override
    public List<Integer> getUserAreaPermission(Integer areaNumber) {
        return apMapper.getUserAreaPermissionByNumber(areaNumber);
    }

    @Override
    public List<Integer> getUserPermission(Integer userID) {
        return userMapper.getUserPermissionsById(userID);
    }

    @Override
    public List<Integer> endPermission(List<Integer> area, List<Integer> user) {
        List<Integer> end = new ArrayList<>();
        //去重 地域的权限要多一些
        for (Integer integer : user) {
            if (area.contains(integer)) {
                end.add(integer);
            }
        }
        return end;
    }

    @Override
    public UserMessage userLoginByName(String userName, String userPassword) {
        return userMapper.userLoginByName(userName, userPassword);
    }


    /**
     * @param
     * @return
     * @Desciption 根据用户名和密码 得到用户的状态
     */
    @Override
    public Integer getStatus(String userName, String userPassword) {
        return userMapper.getStatus(userName, userPassword);
    }

    @Override
    public BaseResponse<JSONObject> getAllUserByPage(long current, long limit, UserQuery userQuery, HttpServletRequest request) {
        Page page = new Page(current, limit);
        //根据redis 拿到地域信息
        String token = request.getHeader("Authorization");
        if (token == null) {
            return setResultError("token失效");
        }
        String infos = redisUtil.getString(token);
        UserMessage info = JSONObject.parseObject(infos, UserMessage.class);
        Integer number = info.getAreaNumber();
        Integer userId = info.getUserId();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        List<Integer> userIds = null;
        List<User> users = new ArrayList<>();
        List<UserAll> userAllList = new ArrayList<>();
        //现在是有了地域号码
        String userName = null;
        String userPhone = null;
        Integer roleId = null;
        if (userQuery != null) {
            userName = userQuery.getUserName();
            userPhone = userQuery.getUserPhone();
            roleId = userQuery.getRoleId();
            if (roleId == null || roleId == 0) {
                roleId = null;
            }
        }
        if (!StringUtils.isEmpty(userName)) {
            wrapper.like("user_name", userName);
        }
        if (!StringUtils.isEmpty(userPhone)) {
            wrapper.like("user_phone", userPhone);
        }
        int flag = 0;
        if (!StringUtils.isEmpty(roleId)) {
            //根据传入的roleId来拿到这个角色小所有的用户Id
            userIds = userRoleMapper.getUserIdsByRoleId(roleId);
            if (userIds.size() == 0) {
                flag = 1;
            }
            wrapper.in("user_id", userIds);
        }
        if (flag == 1) {
            userMapper.selectPage(page, wrapper);
        } else {
            wrapper.eq("area_number", number).ne("user_id", userId);
            IPage iPage = userMapper.selectPage(page, wrapper);
            users = iPage.getRecords();
        }
        for (User user : users) {
            UserAll userAll = new UserAll();
            BeanUtils.copyProperties(user, userAll);
            //获得每个用户的角色
            Integer id = user.getUserId();
            Integer role_id = userRoleMapper.selectRoleIdByUserId(id);
            String areaName = areaMapper.selectNameByNumber(number);
            userAll.setAreaName(areaName);
            //根据role_id查询用户的角色
            String role_Name = roleMapper.getRoleNameByRoleId(role_id);
            UserRoleDTO userRole = new UserRoleDTO();
            userRole.setRoleId(role_id);
            userRole.setRoleName(role_Name);
            userAll.setUserRole(userRole);

            userAllList.add(userAll);

        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", userAllList.size());
        jsonObject.put("userList", userAllList);
        return setResultSuccess(jsonObject);
    }
}

